package com.example.showcase.server;

import com.example.showcase.common.ShowcaseAbsAioHandler;
import com.example.showcase.common.ShowcasePacket;
import com.example.showcase.common.AbstractBizHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tanyaowu
 */
public class ShowcaseServerAioHandler extends ShowcaseAbsAioHandler implements ServerAioHandler {
    private static Logger log = LoggerFactory.getLogger(ShowcaseServerAioHandler.class);

    private Map<Byte, AbstractBizHandler<?>> handlerMap = new HashMap<>();

    /**
     * 处理消息
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        ShowcasePacket showcasePacket = (ShowcasePacket) packet;
        Byte type = showcasePacket.getType();
        AbstractBizHandler<?> showcaseBsHandler = handlerMap.get(type);
        if (showcaseBsHandler == null) {
            log.error("{}, 找不到处理类，type:{}", channelContext, type);
            return;
        }
        showcaseBsHandler.handler(showcasePacket, channelContext);
        return;
    }

    public Map<Byte, AbstractBizHandler<?>> getHandlerMap() {
        return handlerMap;
    }

    public void setHandlerMap(Map<Byte, AbstractBizHandler<?>> handlerMap) {
        this.handlerMap = handlerMap;
    }
}
